﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Reflection;
using System.Collections;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace iwss.Document
{
    public static class Extensions
    {
        public static bool IsNullOrEmpty(this string item)
        {
            return string.IsNullOrEmpty(item.EToString());
        }
        public static string EToString(this object item)
        {
            if (item == null)
                return string.Empty;
            else
                return item.ToString().Trim();
        }

        public static string SubString(this string str, int count)
        {
            if (str.Length > count)
            {
                return str.Substring(0, count) + "...";
            }
            return str;
        }
        /// <summary>
        /// 取值通用方法
        /// </summary>
        public static object TryGetValue(this object obj, string field)
        {
            if (obj == null) return string.Empty;

            PropertyInfo fieldPro = obj.GetType().GetProperty(field);
            if (fieldPro != null)
                return fieldPro.GetValue(obj, null);

            return string.Empty;
        }

        public static void Notify(this Page self, string msg, string level)
        {
            self.ExcuseScript(string.Format("SP.UI.Notify.addNotification(\"{0}\", false);", msg));
        }

        public static void OKAndCloseDlg(this Page self)
        {
            self.OKAndCloseDlg(string.Empty);
        }

        public static void OKAndCloseDlg(this Page self, string retVal)
        {
            var script = "<script type='text/javascript'>";
            script += "    function closeDlg(){";
            script += "    SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.OK, '" + retVal + "');";
            script += "    }";
            script += "    ExecuteOrDelayUntilScriptLoaded(closeDlg, 'sp.js');";
            script += "    window.frameElement.commitPopup('" + retVal + "');";
            script += "</script>";
            self.ClientScript.RegisterClientScriptBlock(self.GetType(), "closeDlg", script);
        }

        public static void AlertAndClose(this Page self, string msg)
        {
            self.Alert(msg);
            self.CancelAndCloseDlg();
        }

        public static void Alert(this Page self, string msg)
        {
            ExcuseScript(self, string.Format("alert('{0}');", msg));
        }

        public static void ExcuseScript(this Page self, string scr)
        {
            string script = "    function actScript(){";
            script += scr;
            script += "    }";
            script += "    ExecuteOrDelayUntilScriptLoaded(actScript, 'sp.js');";

            self.ClientScript.RegisterClientScriptBlock(self.GetType(), "excuseScript", script, true);
        }

        public static void CancelAndCloseDlg(this Page self)
        {
            var script = "<script type='text/javascript'>";
            script += "    function closeDlg(){";
            script += "    SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.cancel, '');";
            script += "    }";
            script += "    ExecuteOrDelayUntilScriptLoaded(closeDlg, 'sp.js');";
            script += "</script>";


            if (string.IsNullOrEmpty(self.Request["IsDlg"]))
            {
                self.ClientScript.RegisterClientScriptBlock(self.GetType(), "closePage", "<script>window.close();</script>");
            }
            else
            {
                self.ClientScript.RegisterClientScriptBlock(self.GetType(), "closeDlg", script);
            }
        }


        /// <summary>
        /// 处理URL为绝对地址
        /// /Lists/Tasks 转换为 http://moss/Lists/Tasks
        /// </summary>
        /// <param name="listUrl">Example: /Lists/Tasks</param>
        /// <returns></returns>
        public static string FixUrl(string listUrl)
        {
            return Microsoft.SharePoint.Utilities.SPUtility.GetServerRelativeUrlFromPrefixedUrl("~site" + listUrl);
        }
    }

    public static class CheckedExtensions
    {

        public static IEnumerable<TreeNode> All(this TreeNodeCollection controls)
        {
            foreach (TreeNode control in controls)
            {
                foreach (var grandchild in control.ChildNodes.All())
                    yield return grandchild;

                yield return control;
            }
        }

        public static IEnumerable<T> AllOfType<T>(this TreeNodeCollection controls) where T : TreeNode
        {
            foreach (TreeNode control in controls)
            {
                foreach (var grandchild in control.ChildNodes.AllOfType<T>())
                    yield return grandchild;

                if (control is T)
                    yield return control as T;
            }
        }
    }

    public static class ControlExtensions
    {
        public static IEnumerable<Control> All(this ControlCollection controls)
        {
            foreach (Control control in controls)
            {
                foreach (var grandchild in control.Controls.All())
                    yield return grandchild;

                yield return control;
            }
        }

        public static IEnumerable<T> AllOfType<T>(this ControlCollection controls) where T : Control
        {
            foreach (Control control in controls)
            {
                foreach (var grandchild in control.Controls.AllOfType<T>())
                    yield return grandchild;

                if (control is T)
                    yield return control as T;
            }
        }

        public static IEnumerable<T> AllOfTypeNoRecursion<T>(this ControlCollection controls) where T : Control
        {
            foreach (Control control in controls)
            {
                if (control is T)
                    yield return control as T;

                foreach (var grandchild in control.Controls.AllOfTypeNoRecursion<T>())
                    yield return grandchild;
            }
        }
    }

    public static class DataTableExtensions
    {
        /// <summary>
        /// 转化一个DataTable
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        /// <returns></returns>
        public static DataTable ToDataTable<T>(this IEnumerable<T> list)
        {
            //创建属性的集合
            List<PropertyInfo> pList = new List<PropertyInfo>();
            //获得反射的入口
            Type type = typeof(T);
            DataTable dt = new DataTable();
            //把所有的public属性加入到集合 并添加DataTable的列
            Array.ForEach<PropertyInfo>(type.GetProperties(), p => { pList.Add(p); dt.Columns.Add(p.Name, p.PropertyType); });
            foreach (var item in list)
            {
                //创建一个DataRow实例
                DataRow row = dt.NewRow();
                //给row 赋值
                pList.ForEach(p => row[p.Name] = p.GetValue(item, null));
                //加入到DataTable
                dt.Rows.Add(row);
            }
            return dt;
        }

        /// <summary>
        /// DataTable 转换为List 集合
        /// </summary>
        /// <typeparam name="TResult">类型</typeparam>
        /// <param name="dt">DataTable</param>
        /// <returns></returns>
        public static List<T> ToList<T>(this DataTable dt) where T : class, new()
        {
            //创建一个属性的列表
            List<PropertyInfo> prlist = new List<PropertyInfo>();
            //获取TResult的类型实例  反射的入口
            Type t = typeof(T);
            //获得TResult 的所有的Public 属性 并找出TResult属性和DataTable的列名称相同的属性(PropertyInfo) 并加入到属性列表 
            Array.ForEach<PropertyInfo>(t.GetProperties(), p => { if (dt.Columns.IndexOf(p.Name) != -1) prlist.Add(p); });
            //创建返回的集合
            List<T> oblist = new List<T>();

            foreach (DataRow row in dt.Rows)
            {
                //创建TResult的实例
                T ob = new T();
                //找到对应的数据  并赋值
                prlist.ForEach(p => { if (row[p.Name] != DBNull.Value) p.SetValue(ob, row[p.Name], null); });
                //放入到返回的集合中.
                oblist.Add(ob);
            }
            return oblist;
        }


        /// <summary>
        /// 将集合类转换成DataTable
        /// </summary>
        /// <param name="list">集合</param>
        /// <returns></returns>
        public static DataTable ToDataTableTow(IList list)
        {
            DataTable result = new DataTable();
            if (list.Count > 0)
            {
                PropertyInfo[] propertys = list[0].GetType().GetProperties();
                foreach (PropertyInfo pi in propertys)
                {
                    result.Columns.Add(pi.Name, pi.PropertyType);
                }

                for (int i = 0; i < list.Count; i++)
                {
                    ArrayList tempList = new ArrayList();
                    foreach (PropertyInfo pi in propertys)
                    {
                        object obj = pi.GetValue(list[i], null);
                        tempList.Add(obj);
                    }
                    object[] array = tempList.ToArray();
                    result.LoadDataRow(array, true);
                }
            }
            return result;
        }

        /**/
        /// <summary>
        /// 将泛型集合类转换成DataTable
        /// </summary>
        /// <typeparam name="T">集合项类型</typeparam>
        /// <param name="list">集合</param>
        /// <returns>数据集(表)</returns>
        public static DataTable ToDataTable<T>(IList<T> list)
        {
            return ToDataTable<T>(list, null);
        }

        /**/
        /// <summary>
        /// 将泛型集合类转换成DataTable
        /// </summary>
        /// <typeparam name="T">集合项类型</typeparam>
        /// <param name="list">集合</param>
        /// <param name="propertyName">需要返回的列的列名</param>
        /// <returns>数据集(表)</returns>
        public static DataTable ToDataTable<T>(IList<T> list, params string[] propertyName)
        {
            List<string> propertyNameList = new List<string>();
            if (propertyName != null)
                propertyNameList.AddRange(propertyName);

            DataTable result = new DataTable();
            if (list.Count > 0)
            {
                PropertyInfo[] propertys = list[0].GetType().GetProperties();
                foreach (PropertyInfo pi in propertys)
                {
                    if (propertyNameList.Count == 0)
                    {
                        result.Columns.Add(pi.Name, pi.PropertyType);
                    }
                    else
                    {
                        if (propertyNameList.Contains(pi.Name))
                            result.Columns.Add(pi.Name, pi.PropertyType);
                    }
                }

                for (int i = 0; i < list.Count; i++)
                {
                    ArrayList tempList = new ArrayList();
                    foreach (PropertyInfo pi in propertys)
                    {
                        if (propertyNameList.Count == 0)
                        {
                            object obj = pi.GetValue(list[i], null);
                            tempList.Add(obj);
                        }
                        else
                        {
                            if (propertyNameList.Contains(pi.Name))
                            {
                                object obj = pi.GetValue(list[i], null);
                                tempList.Add(obj);
                            }
                        }
                    }
                    object[] array = tempList.ToArray();
                    result.LoadDataRow(array, true);
                }
            }
            return result;
        }
    }
}
